package repository

import (
	"context"
	"fmt"
	"github.com/spf13/viper"
	"gopkg.in/gomail.v2"
	"gquickstarter/pkg/cache"
)

type IEmailRepository interface {
	CreateEmailCheckCode(ctx context.Context, email string, code string) error
}

type EmailRepository struct {
	dialer *gomail.Dialer
	sender string
	ca     cache.ECache
}

func CreateEmailRepository(viper *viper.Viper, cache cache.ECache) IEmailRepository {
	dialer := gomail.NewDialer(
		viper.GetString("email.host"),
		viper.GetInt("email.port"),
		viper.GetString("email.username"),
		viper.GetString("email.password"))

	return &EmailRepository{dialer: dialer, sender: viper.GetString("email.username"), ca: cache}
	//return &EmailRepository{}
}

func (e EmailRepository) CreateEmailCheckCode(ctx context.Context, email string, code string) error {
	//add := time.Duration(-1)
	s, err := e.ca.Set(ctx, "aaa", code, -1)
	if err != nil {
		return err
	}
	println(s)
	m := gomail.NewMessage()
	m.SetHeader("From", "moonight@email.cn")
	m.SetHeader("To", email)
	m.SetAddressHeader("Cc", "1017504510@qq.com", "Dan")
	m.SetHeader("Subject", "Hello!")
	//m.SetBody("text/html", "Hello <b>Bob</b> and <i>Cora</i>!")
	m.SetBody("text/html", fmt.Sprintf("你好，你的邮箱验证码为：<br><h2>%s</h2>", code))
	//message.Reset()
	return e.dialer.DialAndSend(m)
}
